<template>
  <van-field
    :label="titleText(options, item)"
    :name="item.itemTitle"
    :required="item.isRequired === 'Y'"
    :rules="[
      { required: item.isRequired === 'Y', message: '请上传' + item.itemTitle },
    ]"
    class="upload_file"
    label-width="33rem"
  >
    <template #input>
      <p v-if="options.showDesc" class="desc f12 mb10">
        {{ options.description }}
      </p>
      <van-uploader
        v-model="fileList"
        :accept="options.isType ? options.fileTypes.toString() : '*'"
        :after-read="afterRead"
        :before-delete="beforeDelete"
        :before-read="beforeRead"
        :deletable="type !== 'view'"
        :disabled="type === 'view'"
        :max-count="options.limit || 1"
        :max-size="fileSize * 1024 * 1024"
        @oversize="onOversize"
      >
        <van-button :disabled="type === 'view'" icon="plus" type="primary"
        >上传文件
        </van-button>
      </van-uploader>
    </template>
  </van-field>
</template>

<script setup>
import { titleText } from "@/utils/common.js";
import { showToast } from "vant";
import { ref, } from "vue";

//defineOptions({ name: "H5FileUpload" });

const { item, type } = defineProps(["item", "type"]);
const emits = defineEmits(["change"]);

const { options } = JSON.parse(item.vformJson);
const fileList = ref(item.value);
const fileSize = options.fileMaxSize || 5;
// [".doc", ".docx", ".pdf", ".xls", ".xlsx"]
// const fileType = (options.fileTypes||[]).map(item => '.'+item)

// 上传文件前
const beforeRead = (file) => {
  let fileType = file.name.split(".").pop().toLowerCase();
  if (options.isType && options.fileTypes.toString().indexOf(fileType) === -1) {
    showToast(`请上传 ${(options.fileTypes || []).join(",")} 格式文件`);
    return false;
  }
  return true;
};
// 此时可以自行将文件上传至服务器
const afterRead = () => {
  item.value = fileList.value;
  onChange();
};
// 传递值改变后
const onChange = () => emits("change", item);

// 文件大小不能超过
const onOversize = (file) => {
  showToast("文件大小不能超过 " + fileSize + "M");
};
// 删除
const beforeDelete = (file, n) => {
  fileList.value.splice(n.index, 1);
  afterRead();
};
</script>

<style lang="less" scoped>
.upload_file {
  :deep(.van-uploader__file) {
    width: 100%;
    flex-direction: inherit;
    height: 5rem;
  }

  :deep(.van-uploader),
  :deep(.van-uploader__preview) {
    flex: 1;
    width: 29rem;
  }

  :deep(.van-uploader__file-icon) {
    margin-left: 1rem;
  }

  :deep(.van-uploader__file-name) {
    margin-top: 0;
    text-align: left;
  }

  :deep(.van-uploader__wrapper) {
    display: block;
  }
}
</style>